Page({
  data: {
    workers: [] // 存储按工人分类的任务
  },

  onLoad(options) {
    console.log('Page onLoad');
    this.getTasksByDate(); // 获取当前日期的所有任务
  },

  onReady() {
    console.log('Page onReady');
  },

  getTasksByDate() {
    const db = wx.cloud.database();
    const today = this.getTodayDate();
    db.collection('tasks').where({
      date: today
    }).get({
      success: res => {
        console.log('从数据库读取任务数据成功', res.data);
        const tasksByWorker = this.groupTasksByWorker(res.data);
        this.setData({
          workers: tasksByWorker
        });
      },
      fail: err => {
        console.error('从数据库读取任务数据失败', err);
      }
    });
  },

  groupTasksByWorker(tasks) {
    const workers = {};
    tasks.forEach(task => {
      const workerId = task.workerId;
      if (!workers[workerId]) {
        workers[workerId] = {
          id: workerId,
          name: task.workerName, // 假设任务对象中包含工人姓名
          tasks: []
        };
      }
      workers[workerId].tasks.push(task);
    });
    return Object.values(workers);
  },

  getTodayDate() {
    const now = new Date();
    return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
  },

  // 新增：打回任务函数
  rejectTask(event) {
    const { workerIndex, taskIndex } = event.currentTarget.dataset;
    const workers = this.data.workers.map((worker, i) => {
      if (i === workerIndex) {
        const tasks = worker.tasks.map((task, j) => {
          if (j === taskIndex) {
            console.log('打回任务:', task);
            return { ...task, accepted: false, completed: false };
          }
          return task;
        });
        return { ...worker, tasks };
      }
      return worker;
    });
    this.setData({
      workers
    }, () => {
      console.log('打回任务后，当前 workers 数据:', this.data.workers);
    });

    // 同步更新数据库
    this.updateTaskInDatabase(workerIndex, taskIndex);
  },

  // 同步更新数据库
  updateTaskInDatabase(workerIndex, taskIndex) {
    const worker = this.data.workers[workerIndex];
    const task = worker.tasks[taskIndex];
    const db = wx.cloud.database();
    db.collection('tasks').doc(task._id).update({
      data: {
        accepted: false,
        completed: false
      },
      success: res => {
        console.log('任务状态更新成功', res);
      },
      fail: err => {
        console.error('任务状态更新失败', err);
      }
    });
  }
});